<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>创建一个日历</title>
		<style>
			table {
				border-collapse: collapse;
			}

			td,
			th {
				border: 1px solid black;
				padding: 3px;
				text-align: center;
			}

			th {
				font-weight: bold;
				background-color: #e6e6e6;
			}
		</style>
	</head>
	<body>
		<div id="calendar"></div>

		<script>
			// function createCalendar(elem, year, month) {
			// 	const d = new Date(year, month - 1)
			// 	console.log(d.getDate())
			// 	console.log(d.getDay())
			// 	const weeks = ['一', '二', '三', '四', '五', '六', '日']

			// 	// 表头
			// 	const th = document.createElement('th')
			// 	weeks.forEach((week) => {
			// 		let td = document.createElement('td')
			// 		td.innerHTML = week
			// 		th.append(td)
			// 	})

			// 	// 渲染表格
			// 	const table = document.createElement('table')
			// 	table.append(th)

			// 	// 日期
			// 	while (true) {
			// 		const day = d.getDate() // 当前月的第几天
			// 		const week = d.getDay() // 当前月当天的星期几
			// 		const nowMonth = d.getMonth() // 当前月份
			// 		const nextMonth = d.getMonth() + 1 // 下月月份

			// 		if (nowMonth >= nextMonth) break

			// 		if (week === 0) {
			// 			const tr = document.createElement('tr')
			// 		} else {
			// 			const tr = document.createElement('tr')

			// 			weeks.forEach((week) => {
			// 				const td = document.createElement('td')
			// 				const isWeek = weeks.at(week - 1)
			// 				td.innerHTML = isWeek === week ? day : ''
			// 				tr.append(td)
			// 				d.setDate(day + 1)
			// 				table.append(tr)
			// 			})
			// 		}
			// 	}

			// 	elem.append(table)
			// }

			function createCalendar(elem, year, month) {
				const d = new Date(year, month - 1)
				console.log(d.getDate())
				console.log(d.getDay())
				const weeks = ['一', '二', '三', '四', '五', '六', '日']

				// 表头
				const tr = document.createElement('tr')
				weeks.forEach((week) => {
					const th = document.createElement('th')
					th.innerHTML = week
					tr.append(th)
				})

				// 渲染表格
				const table = document.createElement('table')
				table.append(tr)

				// 日期
				let day = 1
				while (true) {
					const tr = document.createElement('tr')
					for (let i = 0; i < 7; i++) {
						const td = document.createElement('td')
						if (i >= d.getDay() && day <= new Date(year, month).getDate()) {
							td.innerHTML = day
							day++
						}
						tr.append(td)
					}
					table.append(tr)
					if (day > new Date(year, month).getDate()) break
					d.setMonth(month)
					d.setDate(day)
				}

				elem.append(table)
			}
			createCalendar(calendar, 2012, 9)
		</script>
	</body>
</html>
